/*            Copyright(c) 2006-2008 Dave Sexton           *
 * http://www.codeplex.com/DocProject                      *
 * http://www.codeplex.com/DocProject/Project/License.aspx *
 ***********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Xml.XPath;
using System.ComponentModel.Design;

namespace DaveSexton.DocProject.Sandcastle.BuildComponents.TypeConverters.BuiltIn
{
	internal enum ReferenceLinkType
	{
		None,
		Local,
		Index,
		MSDN
	}

	internal sealed class ResolveReferenceLinksComponent2TypeConverter : TypeConverter
	{
		#region Public Properties
		#endregion

		#region Private / Protected
		#endregion

		#region Constructors
		/// <summary>
		/// Constructs a new instance of the <see cref="ResolveReferenceLinksComponent2TypeConverter" /> class.
		/// </summary>
		public ResolveReferenceLinksComponent2TypeConverter()
		{
		}
		#endregion

		#region Methods
		private IEnumerable<ReferenceTarget> GetTargets(IXPathNavigable navigable)
		{
			if (navigable != null)
			{
				XPathNavigator navigator = navigable.CreateNavigator();

				foreach (XPathNavigator node in navigator.SelectChildren("targets", ""))
					yield return new ReferenceTarget(node);
			}
		}

		public override bool GetPropertiesSupported(ITypeDescriptorContext context)
		{
			return true;
		}

		public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
		{
			PropertyDescriptorCollection properties = new PropertyDescriptorCollection(null);

			int i = 0;
			foreach (ReferenceTarget target in GetTargets(value as IXPathNavigable))
				properties.Add(new ReferenceTargetPropertyDescriptor("Target" + i++, target, context));

			return properties;
		}

		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{
			if (destinationType == typeof(string))
			{
				StringBuilder builder = new StringBuilder("{");

				foreach (ReferenceTarget target in GetTargets(value as IXPathNavigable))
					builder.AppendFormat(System.Globalization.CultureInfo.CurrentCulture, "{0}, ", target.LinkType);

				if (builder.Length > 1)
					// remove trailing comma and space
					builder.Remove(builder.Length - 2, 2);

				builder.Append('}');

				return builder.ToString();
			}
			else
				return base.ConvertTo(context, culture, value, destinationType);
		}
		#endregion
	}
}
